<?php
/**
 * Direct Import da altro meta-base
 * in file const.inc.php are defined URL (aRemoteDB) 
 */
require_once("../../../config.inc.php");
$isReloadable = true;
require_once(SERVER_FS_ROOT."/app/_inc/include.php");
require_once(SERVER_FS_ROOT."/app/_inc/sxHttpClient.class.php");
require_once(SERVER_FS_ROOT."/app/util/imex/_inc/importExport.func.php");

$errMsg = sxREQ('msg');

$objUser = $_SESSION[USEROBJ];
$aDataArea = $objUser->getDataArea();
$aRemoteRisp = array('mod'=>array(),'sub'=>array(),'process_unit'=>array(),'menu_page'=>array(),
	'data_area'=>array(),'subject_area'=>array(),'entity'=>array(),'relationship'=>array());
if(sxREQ("reqtype") == "load"){	
	$errMsg .= loadMb();
	if (sxREQUEST('mb_ref') == 'menu_page') {
		$errMsg .= getMenu($aRemoteRisp);
	} elseif (sxREQUEST('mb_ref') == 'process_unit') {
		$errMsg .= getPU($aRemoteRisp);
	} elseif (sxREQUEST('mb_ref') == 'entity') {
		$errMsg .= getEntity($aRemoteRisp);
	} elseif (sxREQUEST('mb_ref') == 'relationship') {
		$errMsg .= getRelationship($aRemoteRisp);
	}
}
if(sxREQ("reqtype") == "cser"){	
	$errMsg .= getContact();
}
if(sxREQ("reqtype") == "cref"){	
	if (sxREQUEST('mb_ref') == 'entity' or sxREQUEST('mb_ref') == 'relationship') {
		$errMsg .= getDataArea($aRemoteRisp);
	} else {
		$errMsg .= getModule($aRemoteRisp);
	}
}
if(sxREQ("reqtype") == "cmod"){	
	if (sxREQUEST('mb_ref') == 'menu_page') {
		$errMsg .= getMenu($aRemoteRisp);
	} else {
		$errMsg .= getSubMod($aRemoteRisp);
	}
}
if(sxREQ("reqtype") == "csub"){	
	$errMsg .= getPU($aRemoteRisp);
}
if(sxREQ("reqtype") == "cdta"){	
	$errMsg .= getSubjectArea($aRemoteRisp);
}
if(sxREQ("reqtype") == "csua"){	
	if (sxREQUEST('mb_ref') == 'entity') {
		$errMsg .= getEntity($aRemoteRisp);
	} else {
		$errMsg .= getRelationship($aRemoteRisp);
	}
}
//dbg_("aRemoteRisp=",print_r($aRemoteRisp,1));


$aOpz = array("kMenu"=>"uti.dum", "isReloadable"=>$isReloadable);
echo(headerHTML($aOpz));
?>
<script language="JavaScript" type="text/javascript">
function caricaMB() {
	document.objFrm.reqtype.value = 'load';
	document.objFrm.submit();
}
function newServer() {
	if (document.objFrm.mb_ref) document.objFrm.mb_ref.value = '';
	if (document.objFrm.mb_mod) document.objFrm.mb_mod.value = '';
	if (document.objFrm.mb_sub) document.objFrm.mb_sub.value = '';
	if (document.objFrm.mb_dta) document.objFrm.mb_dta.value = '';
	if (document.objFrm.mb_sua) document.objFrm.mb_sua.value = '';
	document.objFrm.reqtype.value = 'cser';
	document.objFrm.submit();
}
function newRef() {
	if (document.objFrm.mb_mod) document.objFrm.mb_mod.value = '';
	if (document.objFrm.mb_sub) document.objFrm.mb_sub.value = '';
	if (document.objFrm.mb_dta) document.objFrm.mb_dta.value = '';
	if (document.objFrm.mb_sua) document.objFrm.mb_sua.value = '';
	document.objFrm.reqtype.value = 'cref';
	document.objFrm.submit();
}
function newModule() {
	if (document.objFrm.mb_sub) document.objFrm.mb_sub.value = '';
	if (document.objFrm.mb_dta) document.objFrm.mb_dta.value = '';
	if (document.objFrm.mb_sua) document.objFrm.mb_sua.value = '';
	document.objFrm.reqtype.value = 'cmod';
	document.objFrm.submit();
}
function newSubMod() {
	if (document.objFrm.mb_dta) document.objFrm.mb_dta.value = '';
	if (document.objFrm.mb_sua) document.objFrm.mb_sua.value = '';
	document.objFrm.reqtype.value = 'csub';
	document.objFrm.submit();
}
function newDataArea() {
	if (document.objFrm.mb_mod) document.objFrm.mb_mod.value = '';
	if (document.objFrm.mb_sub) document.objFrm.mb_sub.value = '';
	if (document.objFrm.mb_sua) document.objFrm.mb_sua.value = '';
	document.objFrm.reqtype.value = 'cdta';
	document.objFrm.submit();
}
function newSubjectArea() {
	if (document.objFrm.mb_mod) document.objFrm.mb_mod.value = '';
	if (document.objFrm.mb_sub) document.objFrm.mb_sub.value = '';
	document.objFrm.reqtype.value = 'csua';
	document.objFrm.submit();
}
function setExp() {
	for(k=1;k<1000;k++) {
		oExp = document.getElementById('exp_'+String(k));
		if (!oExp) break;
		oExp.checked = document.objFrm.set_exp.checked;
	}
}
</script>
  
<?php
echo(bodyHTML($aOpz));

$aCmd = array();
if (count($aRemoteRisp['process_unit']) > 0 
or count($aRemoteRisp['menu_page'])
or count($aRemoteRisp['relationship'])
or count($aRemoteRisp['entity'])) {
	$aCmd["load"] = array("pag"=>"javascript:caricaMB()",
						"title"=>_t("compare selected meta-base"),
						"text"=>_t("compare")
						);
}
$aCmd["back"] = array();

echo(commandsHTML($aCmd));	
?>
<form name='objFrm' id='objFrm' action='<?=$_SERVER['PHP_SELF']?>' method='POST' style='margin:0;'>
<input type='hidden' name='reqtype' id='reqtype' value='---'>
<input type='hidden' name='xsn' value='<?=XSN?>'>
<table class='tabl01' width='100%' cellpadding='3' cellspacing='2' border='0'>
	<tr>
		<td class='titl01' colspan='4'>Remote meta-base compare/import</td>
	</tr>
	<tr>
		<td class='labl01' width='20%'>Remote meta-base</td>
		<td class='text01' width='30%'>
<?
$aOpt = array('onChange'=>'newServer();');
$aVal = array(''=>'-- select meta-base --');
foreach($aRemoteMB as $des => $aRMB) {
	$aVal[$des] = $des;
}
echo getHTMLSelect('mb_url', $aVal, '@REQ', $aOpt);
?>
		</td>
		<td class='labl01' width='20%'>Meta-base section</td>
		<td class='text01' width='30%'>
<?
if (sxREQ('mb_url')=='') {
	echo "&nbsp;";
} else {
	$aOpt = array('onChange'=>'newRef();');
	$aVal = array(''=>'-- select --', 
		'process_unit'=>'process-units',
		'menu_page'=>'menu-pages',
		'entity'=>'entities',
		'relationship'=>'relationships');
	echo getHTMLSelect('mb_ref', $aVal, '@REQ', $aOpt);
}
?>
		</td>
	</tr>
	
	<tr>
<?
if (sxREQ('mb_ref')=='menu_page' or sxREQ('mb_ref')=='process_unit') {
?>
		<td class='labl01' width='20%'>Module</td>
		<td class='text01' width='30%'>
<?
	$aOpt = array('onChange'=>'newModule();');
	$aVal = array(''=>'-- select --');
	foreach($aRemoteRisp['mod'] as $cod => $des) {
		$aVal[$cod] = $des;
	}
	echo getHTMLSelect('mb_mod', $aVal, '@REQ', $aOpt);
?>
		</td>
<?
} elseif (sxREQ('mb_ref')=='entity' or sxREQ('mb_ref')=='relationship') {
?>
		<td class='labl01' width='20%'>Data-Area</td>
		<td class='text01' width='30%'>
<?
	$aOpt = array('onChange'=>'newDataArea();');
	$aVal = array(''=>'-- select --');
	foreach($aRemoteRisp['data_area'] as $cod => $des) {
		$aVal[$cod] = $des;
	}
	echo getHTMLSelect('mb_dta', $aVal, '@REQ', $aOpt);
?>
		</td>
<?
} else {
?>
		<td class='text01' width='50%' colspan='2'>&nbsp;</td>
<?
}
if (sxREQUEST('mb_ref') == 'process_unit') {
	echo "         <td class='labl01' width='20%'>sub-module</td>\n";
	echo "         <td class='text01' width='30%'>\n";
	$aOpt = array('onChange'=>'newSubMod();');
	$aVal = array(''=>'-- select --');
	foreach($aRemoteRisp['sub'] as $cod => $des) {
		$aVal[$cod] = $des;
	}
	if (count($aVal) > 2) {
		$aVal['*'] = '-- all --';
	}
	echo getHTMLSelect('mb_sub', $aVal, '@REQ', $aOpt);
	echo "</td>\n";
} elseif (sxREQUEST('mb_ref') == 'entity') {
	echo "         <td class='labl01' width='20%'>Subject-area</td>\n";
	echo "         <td class='text01' width='30%'>\n";
	$aOpt = array('onChange'=>'newSubjectArea();');
	$aVal = array(''=>'-- select --');
	foreach($aRemoteRisp['subject_area'] as $cod => $des) {
		$aVal[$cod] = $des;
	}
	if (count($aVal) > 2) {
		$aVal['*'] = '-- all --';
	}
	echo getHTMLSelect('mb_sua', $aVal, '@REQ', $aOpt);
	echo "</td>\n";
} elseif (sxREQUEST('mb_ref') == 'relationship') {
	echo "         <td class='labl01' width='20%'>Subject-area</td>\n";
	echo "         <td class='text01' width='30%'>\n";
	$aOpt = array('onChange'=>'newSubjectArea();');
	$aVal = array(''=>'-- select --');
	foreach($aRemoteRisp['subject_area'] as $cod => $des) {
		$aVal[$cod] = $des;
	}
	if (count($aVal) > 2) {
		$aVal['*'] = '-- all --';
	}
	echo getHTMLSelect('mb_sua', $aVal, '@REQ', $aOpt);
	echo "</td>\n";
} else {	
	echo "         <td class='text01' width='50%' colspan='2'>&nbsp;</td>\n";
}
?>
	</tr>
<?
if (sxREQUEST('mb_ref')!= '') {
	if (sxREQUEST('mb_ref') == 'menu_page') {
		$listLab = _t("List of menu-pages");
		$colLab = _t("Pagina men@");
	} elseif (sxREQUEST('mb_ref') == 'entity') {
		$listLab = _t("List of entities");
		$colLab = _t("Entity");
	} elseif (sxREQUEST('mb_ref') == 'relationship') {
		$listLab = _t("List of relationship");
		$colLab = _t("Relreqtype");
	} elseif (sxREQUEST('mb_ref') == 'process_unit') {
		$listLab = _t("List of process-units");
		$colLab = _t("Processo");
	} else {
		$listLab = sxREQUEST('mb_ref');
		$colLab = sxREQUEST('mb_ref');
	}
?>
</table>
<table class='tabl01' width='100%' cellpadding='3' cellspacing='2' border='0'>
	<tr>
		<td class='titl01' colspan='3'><?=$listLab?></td>
	</tr>
	<tr>
		<td class='tabh01' width='1%'>
			<input type='checkbox' name='set_exp' id='set_exp' value="x" onClick='setExp();'>
		</td>
		<td class='tabh01' width='30%'><?=$colLab?></td>
		<td class='tabh01' width='69%'>Descrizione</td>
	</tr>
<?
	$nn = 0;
	foreach($aRemoteRisp[sxREQUEST('mb_ref')] as $cod => $des) {
		$nn++;
?>
	<tr>
		<td class='text01' width='1%'>
			<input type='checkbox' name='exp_<?=$nn?>' id='exp_<?=$nn?>' value="<?=$cod?>">
		</td>
		<td class='text01' width='30%'><?=str_replace('@','.',$cod)?></td>
		<td class='text01' width='69%'><?=$des?></td>
	</tr>
<?
	}
}
?>
</table>
</form>
<?
echo(commandsHTML($aCmd));
echo(footerHTML());
exit();

// connect to remote server
function getContact () {
	global $objUser, $aRemoteMB;
  	$objUser->setHistoryVar(array('reqtype'=>''));
  	if (sxREQUEST('mb_url')=='') return '';
  	$sQueryStr = "tr=contact&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password']);
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
  	return "server connected";
}

// carica lista moduli
function getModule (&$aRemoteRisp) {
	global $objUser, $aRemoteMB;
  	$objUser->setHistoryVar(array('reqtype'=>''));
  	if (sxREQUEST('mb_url')=='') return '';
  	$sQueryStr = "tr=mod&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password']);
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
  	$aRemoteRisp = unserialize($aRisp[1]);
  	if (count($aRemoteRisp['mod'])==0) return _t("No module on %s",sxREQUEST('mb_url'));
  	return "Module list retrieved";
}

//carica lista sotto-moduli
function getSubMod (&$aRemoteRisp) {
	global $objUser, $aRemoteMB;
  	$objUser->setHistoryVar(array('reqtype'=>''));
  	if (sxREQUEST('mb_url')=='') return '';
  	if (sxREQUEST('mb_mod')=='') return '';
  	$sQueryStr = "tr=sub&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password'])."&mod=".sxREQUEST('mb_mod');
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
  	$aRemoteRisp = unserialize($aRisp[1]);
  	//dbg_(print_r($aRemoteSubMod,1));
  	if (count($aRemoteRisp['sub'])==0) return _t("Non esistono sottomoduli di %s",sxREQUEST('mb_mod'));
  	return _t("Sub-module retrieved");
}

//carica lista menu
function getMenu (&$aRemoteRisp) {
	global $objUser, $aRemoteMB;
  	$objUser->setHistoryVar(array('reqtype'=>''));
  	if (sxREQUEST('mb_url')=='') return '';
  	if (sxREQUEST('mb_mod')=='') return '';
  	$sQueryStr = "tr=menu&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password'])."&mod=".sxREQUEST('mb_mod');
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
  	$aRemoteRisp = unserialize($aRisp[1]);
  	//dbg_(print_r($aRemoteSubMod,1));
  	if (count($aRemoteRisp['menu_page'])==0) return _t("Non esistono men@ di %s",sxREQUEST('mb_mod'));
  	return _t("Menu-pages retrieved");
}

//carica lista processi
function getPU (&$aRemoteRisp) {
	global $objUser, $aRemoteMB;
  	if (sxREQUEST('mb_url')=='') return '';
  	if (sxREQUEST('mb_mod')=='') return '';
  	if (sxREQUEST('mb_sub')=='') return '';
  	$sQueryStr = "tr=pu&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password']).
		"&mod=".sxREQUEST('mb_mod')."&sub=".sxREQUEST('mb_sub');
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
  	$aRemoteRisp = unserialize($aRisp[1]);
  	if (count($aRemoteRisp['process_unit'])==0) return _t("No process-units for %s.%s",sxREQUEST('mb_mod'),sxREQUEST('mb_sub'));
  	return _t("Process-units retrieved");
}

//carica lista data area
function getDataArea (&$aRemoteRisp) {
	global $objUser, $aRemoteMB;
  	if (sxREQUEST('mb_url')=='') return '??';
  	$sQueryStr = "tr=da&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password']);
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
  	$aRemoteRisp = unserialize($aRisp[1]);
  	if (count($aRemoteRisp['data_area'])==0) return _t("No Data-Area");
  	return _t("Data_Area retrieved");
}

//carica subject area
function getSubjectArea (&$aRemoteRisp) {
	global $objUser, $aRemoteMB;
  	if (sxREQUEST('mb_url')=='') return '??';
  	if (sxREQUEST('mb_dta')=='') return '??';
  	$sQueryStr = "tr=sa&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password'])."&da=".sxREQUEST('mb_dta');
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
  	$aRemoteRisp = unserialize($aRisp[1]);
  	if (count($aRemoteRisp['subject_area'])==0) return _t("No subject-area for %s",sxREQUEST('mb_dta'));
  	return _t("Subject-area retrieved");
}

//carica entity
function getEntity (&$aRemoteRisp) {
	global $objUser, $aRemoteMB;
  	if (sxREQUEST('mb_url')=='') return '??';
  	if (sxREQUEST('mb_dta')=='') return '??';
   if (sxREQUEST('mb_sua')=='') return '??';
  	$sQueryStr = "tr=ent&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password']).
		"&da=".sxREQUEST('mb_dta')."&sa=".sxREQUEST('mb_sua');
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
  	$aRemoteRisp = unserialize($aRisp[1]);
  	if (count($aRemoteRisp['subject_area'])==0) return _t("Non esistono entity di %s.%s",sxREQUEST('mb_dta'),sxREQUEST('mb_sua'));
  	return _t("Entities retrieved")."<br>";
}

//carica relazioni
function getRelationship (&$aRemoteRisp) {
	global $objUser, $aRemoteMB;
  	if (sxREQUEST('mb_url')=='') return '??';
  	if (sxREQUEST('mb_dta')=='') return '??';
   if (sxREQUEST('mb_sua')=='') return '??';
  	$sQueryStr = "tr=rel&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password']).
		"&da=".sxREQUEST('mb_dta')."&sa=".sxREQUEST('mb_sua');
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
  	$aRemoteRisp = unserialize($aRisp[1]);
  	if (count($aRemoteRisp['subject_area'])==0) return _t("Non esistono relazioni di %s.%s",sxREQUEST('mb_dta'),sxREQUEST('mb_sua'));
  	return _t("Relationships retrieved")."<br>";
}

//carica array dati importreqtype
function loadMB () {
	global $objUser, $objSDAO, $aRemoteMB;
  	if (sxREQUEST('mb_ref')=='') return 'errore - sezione mancante';
  	if (sxREQUEST('mb_url')=='') return 'errore - URL mancante';
	$aReqExp = array(); //array richieste importreqtype
 	foreach($_REQUEST as $key=>$value) {
 		if(substr($key,0,4) == "exp_") {
  			$aReqExp[] = array(sxREQUEST('mb_ref'),$value);
  			$objUser->setHistoryVar(array($key=>''));
 		}
 	}
  	$objUser->setHistoryVar(array('reqtype'=>'')); 
	if (count($aReqExp) == 0) {
		return _t("No item selected")."<br>";
	}
	$serReqExp = urlencode(serialize($aReqExp));
	//richiesta http per ricevere array importreqtype serializzato
  	$sQueryStr = "tr=exp&pwd=".urlencode($aRemoteMB[sxREQUEST('mb_url')]['password'])."&akey=".$serReqExp;
	$aRisp = getRemoteMB($sQueryStr);
	if ($aRisp[0] == 'KO') { return $aRisp[1];}
	// scrittura array serializzato su file temporaneo
 	if (!is_dir(SERVER_FS_TEMP."/imex")) {
 		mkdir(SERVER_FS_TEMP."/imex",0775);
 	}
 	if ($dh = opendir(SERVER_FS_TEMP."/imex")) { //cancella file temporanei vecchi di 2 giorni
 		$ymdLimit = date('ymd',time()-3600*24);
	  	while ($file = readdir($dh)) {
	      if (substr($file,0,3)=='exp' and substr($file,3,6)< $ymdLimit) {
	      	unlink(SERVER_FS_TEMP."/imex/".$file);
	      }
	   }
	   closedir($dh);
	}
 	if (!is_dir(SERVER_FS_TEMP."/imex")) {
 		return _t("Unable to create directory %s",SERVER_FS_TEMP."/imex")."<br>";
 	}
 	$nomeFile = 'exp'.uniqid(date('ymd'));
	if(!file_put_contents(SERVER_FS_TEMP."/imex/$nomeFile.txt", $aRisp[1])) {
 		return _t("Impossible to create file %s",SERVER_FS_TEMP."/imex/$nomeFile.txt")."<br>";
	}
	// redirect alla pagina di confronto / importreqtype
	serverRedir(SERVER_URL_ROOT."/app/util/imex/importMB.php?nf=$nomeFile&xsn=".XSN);
	return '???';
} 

function getRemoteMB($sPost) {
	global $objUser, $objSDAO, $aRemoteMB;
  	if (sxREQUEST('mb_ref')=='') return 'error - missing section'.'<br>';
  	if (sxREQUEST('mb_url')=='') return 'error - missing URL'.'<br>';
  	$URL = $aRemoteMB[sxREQUEST('mb_url')]['pathRoot']."/app/util/imex/remoteResp.php";
  	
	/*/////////////////////////////////////////
  	$httpClient = new sxHttpClient();
  	if (!$httpClient->POST($URL, $sPost, $aRemoteMB[sxREQUEST('mb_url')]['proxy'])) {
  		return array('KO',"$URL<br>$sPost<br>".$httpClient->errno." - ".$httpClient->error.
         "<br>HTTP header: ".implode("<br>",$httpClient->aHeader).
  			"<br>HTTP ret.code: ".$httpClient->retCode.' - '.$httpClient->retDescr."<br>");
  	}
  	$sRisp = $httpClient->content; 	
  	//*////////////////////////////////////////////
  	
  	set_time_limit(40);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$URL."?".$sPost); 		// imposto l'url
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 			// imposto il ritorno del risultato in una variabile
	curl_setopt($ch, CURLOPT_TIMEOUT, 30); 						// imposto il timeout
	$sRisp = curl_exec($ch); 		// eseguo la richiesta
	if (curl_errno($ch) != 0) {
  		return array('KO',"$URL<br>$sPost<br>Errore Http: ".curl_errno($ch));
	}
	curl_close($ch);
	
  	$aRisp = explode("@zxcv@",$sRisp);  	
  	if (count($aRisp)!= 4) {
  		return array('KO',"$URL<br>$sPost<br>Response: $sRisp");
  	}
  	if ($aRisp[1] != 'OK') return array('KO',$aRisp[2].'<br>');
	return array('OK',$aRisp[2]);
}
